import logging
import sys

from jinrongAutoTest.caw.readfile import get_project_path


class Logger:
    def __init__(self):
        self.filename = get_project_path() + f'/log/log.txt'  # 接收日志文件路径
        self.logger = logging.getLogger()  # 创建日志
        self.logger.setLevel("INFO")  # 设置日志级别：DEBUG INFO WARNING ERROR CRITICAL
        # 设置日志输出的内容
        self.formatter = logging.Formatter('[%(asctime)s]-[%(filename)s]-[%(levelname)s]:%(message)s')

    def console(self, level, message):
        # 输出到文件
        fh = logging.FileHandler(self.filename, mode='a', encoding='utf-8') #将格式化的日志写入文件
        # 设置日志格式
        fh.setFormatter(self.formatter)
        # 将内容添加到日志文件
        self.logger.addHandler(fh)
        # 输出到控制台
        sh = logging.StreamHandler(sys.stdout)
        # 设置日志格式
        sh.setFormatter(self.formatter)
        # 将内容添加到控制台
        self.logger.addHandler(sh)

        if level == 'debug':
            self.logger.debug(message)
        elif level == 'info':
            self.logger.info(message)
        elif level == 'warning':
            self.logger.warning(message)
        elif level == 'error':
            self.logger.error(message)
        else:
            self.logger.critical(message)

        # 避免日志重复输出
        self.logger.removeHandler(sh)
        self.logger.removeHandler(fh)
        # 关闭日志文件
        fh.close()

    def debug(self, message):
        self.console('debug', message)

    def info(self, message):
        self.console('info', message)

    def warning(self, message):
        self.console('warning', message)

    def error(self, message):
        self.console('error', message)

    def critical(self, message):
        self.console('critical', message)